package com.hm.common.util;

import java.awt.Image;
import java.awt.Toolkit;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * 
 * 资源工具类
 */
public class ResourceUtil {
	/**
	 * 获取应用路径
	 * @param classLoader
	 * @param imageRelativePath
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@SuppressWarnings("rawtypes")
	public static String getApplicationPath(Class c) throws UnsupportedEncodingException {
		String jarPath = "";
		jarPath = c.getProtectionDomain().getCodeSource().getLocation().getPath();
		jarPath = java.net.URLDecoder.decode(jarPath, "UTF-8");
		String appPath = null;
		try {
			appPath = new File(jarPath).getParentFile().getParentFile().getAbsolutePath();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return appPath;
	}
	
	
	/**
	 * 相对路径获取图片
	 * @param classLoader
	 * @param imageRelativePath
	 * @return
	 */
	public static Image getImage(ClassLoader classLoader, String imageRelativePath) {
		return Toolkit.getDefaultToolkit().createImage(getResourceAsBytes(classLoader, imageRelativePath));
	}
	
	/**
	 * 根据相对路径获取资源文件
	 * @param classLoader
	 * @param resRelativePath
	 * @return
	 */
	public static byte[] getResourceAsBytes(ClassLoader classLoader, String resRelativePath) {
		InputStream is = null;
		ByteArrayOutputStream os = null;
		try {
			is = classLoader.getResourceAsStream(resRelativePath);
			os = new ByteArrayOutputStream();
			int length = -1;
			byte[] buffer = new byte[1024];
			while(-1 != (length = is.read(buffer))){
				os.write(buffer, 0, length);
			}
			return os.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("读取" + resRelativePath + "异常");
		} finally {
			
		}
	}
}